<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '我的预约',
  },
}
</route>
<template>
  <view class="container" :style="containerStyle">
    <!-- 顶部导航 -->
    <view class="top-bar flex items-center justify-between px-4 py-2">
      <view class="nav-back" @click="navigateBack">
        <wd-icon name="thin-arrow-left" size="22px"></wd-icon>
      </view>
      <text class="title font-bold">我的预约记录</text>
      <view class="nav-calendar" @click="showCalendarPicker = true">
        <wd-icon name="calendar" size="22px"></wd-icon>
      </view>
    </view>

    <!-- 年月选择 -->
    <view class="month-select flex justify-center items-center py-4">
      <wd-icon name="left" @click="prevMonth" size="24px"></wd-icon>
      <text class="current-month font-bold">{{ currentYear }}年{{ currentMonth }}月</text>
      <wd-icon name="right" @click="nextMonth" size="24px"></wd-icon>
    </view>

    <!-- 预约统计 -->
    <view class="stats flex justify-around bg-white py-4 mb-3">
      <view class="stat-item text-center">
        <text class="stat-value font-bold">{{ monthDays }}天</text>
        <text class="stat-label">本月预约</text>
      </view>
      <view class="stat-item text-center">
        <text class="stat-value font-bold">{{ continueDays }}天</text>
        <text class="stat-label">连续预约</text>
      </view>
      <view class="stat-item text-center">
        <text class="stat-value font-bold">{{ totalDays }}天</text>
        <text class="stat-label">累计预约</text>
      </view>
    </view>

    <!-- 预约日历（使用wd-calendar-view） -->
    <view class="calendar bg-white p-3 mb-3">
      <wd-calendar-view
        type="date"
        v-model="currentDate"
        :min-date="monthStart"
        :max-date="monthEnd"
        :show-panel-title="false"
        @change="handleCalendarChange"
        :formatter="formatter"
      >
      </wd-calendar-view>
    </view>

    <!-- 月份选择器 -->
    <wd-calendar
      type="month"
      v-model="currentDate"
      @confirm="handleMonthConfirm"
    />

    <!-- 预约记录列表 -->
    <view class="record-list px-3 py-2">
      <view v-for="(record, index) in signRecords" :key="index" class="record-item mb-3">
        <view class="record-top flex justify-between">
          <text class="record-date">{{ record.date }}</text>
          <text class="record-time">{{ record.time }}</text>
        </view>
        <view class="record-bottom flex justify-between mt-2">
          <text class="record-course">课程：{{ record.course }}</text>
          <text class="record-coach">教练：{{ record.coach }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { getSignRecords } from '@/api/sign';

// 日期状态管理（存储为时间戳）
const currentDate = ref(new Date().getTime());
const currentYear = computed(() => new Date(currentDate.value).getFullYear());
const currentMonth = computed(() => new Date(currentDate.value).getMonth() + 1);
const showCalendarPicker = ref(false);

// 当前月份的开始和结束时间戳
const monthStart = computed(() => {
  const date = new Date(currentYear.value, currentMonth.value - 1, 1);
  return date.getTime();
});

const monthEnd = computed(() => {
  const date = new Date(currentYear.value, currentMonth.value, 0);
  return date.getTime();
});

// 预约数据
const monthDays = ref(0);
const continueDays = ref(0);
const totalDays = ref(0);
const signRecords = ref([]);
const loading = ref(false);
const markedDates = ref({}); // 用于标记已预约日期

// 屏幕安全区域适配
let safeAreaInsets: UniApp.SafeAreaInsets | null = null;
let systemInfo: UniApp.GetSystemInfoResult | UniApp.WindowInfo = {} as any;
// #ifdef MP-WEIXIN
systemInfo = uni.getWindowInfo();
safeAreaInsets = systemInfo.safeArea
  ? {
    top: systemInfo.safeArea.top,
    right: systemInfo.windowWidth - systemInfo.safeArea.right,
    bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
    left: systemInfo.safeArea.left,
  }
  : null;
// #endif
// #ifndef MP-WEIXIN
systemInfo = uni.getSystemInfoSync();
safeAreaInsets = systemInfo.safeAreaInsets;
// #endif

const containerStyle = computed(() => ({
  marginTop: safeAreaInsets?.top + 'px',
  'background-color': '#f8e9d6',
}));

// 初始化
onLoad(() => {
  fetchSignRecords();
});

// 生成已预约日期标记
const generateMarkedDates = (records: any[]) => {
  const marks: Record<string, { marked: boolean }> = {};
  records.forEach(record => {
    const date = new Date(record.date);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    // 格式化日期键（如：2023-10-05）
    const key = `${year}-${month}-${day}`;
    marks[key] = { marked: true };
  });
  markedDates.value = marks;
};

// 获取预约记录
const fetchSignRecords = async () => {
  loading.value = true;
  try {
    const params = {
      year: currentYear.value,
      month: currentMonth.value
    };
    const res = await getSignRecords(params);
    if (res.code === 200) {
      signRecords.value = res.data || [];
      monthDays.value = res.data?.length || 0;
      continueDays.value = res.continueDays || 0;
      totalDays.value = res.totalDays || 0;
      generateMarkedDates(res.data || []);
    } else {
      uni.showToast({ title: res.msg || '获取预约记录失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取预约记录失败:', err);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 日历事件处理
const handleCalendarChange = (date) => {
  console.log("datedatedate",date.value)
  currentDate.value =date.value;
  fetchSignRecords();
};

const handleMonthConfirm = (date) => {
  console.log("datedatedate",date.value)
  currentDate.value =date.value;
  showCalendarPicker.value = false;
  fetchSignRecords();
};

const handleDayClick = (date: { year: number; month: number; day: number }) => {
  // 可添加日期点击事件（如查看当天详情）
  console.log('点击日期:', date);
};

const formatter = (day) => {
  const date = new Date(day.date)
  const now = new Date()

  const year = date.getFullYear()
  const month = date.getMonth()
  const da = date.getDate()
  const nowYear = now.getFullYear()
  const nowMonth = now.getMonth()
  const nowDa = now.getDate()

  if (year === nowYear && month === nowMonth && da === nowDa) {
    day.topInfo = '今天'
  }
  return day
}

// 月份切换
const prevMonth = () => {
  const prevDate = new Date(currentYear.value, currentMonth.value - 2, 1);
  currentDate.value = prevDate.getTime();
  fetchSignRecords();
};

const nextMonth = () => {
  const nextDate = new Date(currentYear.value, currentMonth.value, 1);
  currentDate.value = nextDate.getTime();
  fetchSignRecords();
};

// 返回逻辑
const navigateBack = () => {
  const pages = getCurrentPages();
  if (pages.length <= 1) {
    uni.redirectTo({ url: '/pages/about/index' });
  } else {
    uni.navigateBack({ delta: 1 });
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
}

.top-bar {
  background-color: rgba(245, 230, 216, 0.9);
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
}

.nav-back, .nav-calendar {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
}

.title {
  color: #333;
  font-size: 36rpx;
}

.month-select {
  background-color: white;
  border-bottom: 1px solid #eee;
}

.current-month {
  margin: 0 40rpx;
  font-size: 32rpx;
}

.stats {
  border-bottom: 1px solid #eee;
}

.stat-value {
  font-size: 40rpx;
  color: #b32414;
}

.stat-label {
  font-size: 28rpx;
  color: #666;
}

.day-item {
  width: 100%;
  height: 80rpx;
}

.day-number {
  font-size: 28rpx;
}

.day-status {
  font-size: 20rpx;
  margin-top: 4rpx;
}

.record-list {
  margin-top: 10rpx;
}

.record-item {
  background: linear-gradient(to right, #b34f44, #fab7ad);
  border-radius: 12rpx;
  padding: 20rpx;
  color: #fff;
}

.record-date, .record-time, .record-course, .record-coach {
  font-size: 28rpx;
}

/* 隐藏日历默认标题栏 */
::v-deep .wd-calendar-view__header {
  display: none;
}

/* 调整星期标题样式 */
::v-deep .wd-calendar-view__weekdays {
  padding: 10rpx 0;
}

::v-deep .wd-calendar-view__weekday {
  color: #666;
  font-size: 28rpx;
}
</style>
